//
//  KDOverwideNavigationController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 16/3/14.
//  Copyright © 2016年 魏强. All rights reserved.
//

#import "KDOverwideNavigationController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
@interface KDOverwideNavigationController ()<UIWebViewDelegate, UISearchBarDelegate, NJKWebViewProgressDelegate>
{
    UIWebView *webview;
    UIButton *backButton;
    NSInteger isBackMain; // 判断是否返回主界面
    UIActivityIndicatorView *activityIndicator;
    NSString *webUrl;
    NJKWebViewProgressView *_webViewProgressView;
    NJKWebViewProgress *_webViewProgress;
}
@end

@implementation KDOverwideNavigationController
#pragma mark - 生命周期区
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    //处理内存
    int cacheSizeMemory = 4*1024*1024; // 4MB
    int cacheSizeDisk = 32*1024*1024; // 32MB
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
    [NSURLCache setSharedURLCache:sharedCache];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self isFirstOrNot];
    webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, screenW, screenH - 49)];
    webview.backgroundColor = BackGroundColor;
    webview.scalesPageToFit = YES;
    webview.delegate = self;
    [self.view addSubview: webview];

    [self setupNav];
    isBackMain = 1;
//    [self.view addSubview:activityIndicator];
    webview.scrollView.bounces = YES;
    //设置滚动条的显示
    //水平滚动条
    webview.scrollView.showsHorizontalScrollIndicator = NO;
    //垂直滚动条
    webview.scrollView.showsVerticalScrollIndicator = NO;
    NSURLRequest *request =[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:webUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    [webview loadRequest:request];
    
    backButton = [UIButton buttonWithType:0];
    backButton.frame = CGRectMake(0, 0, 30, 30);
    [backButton setImage:[UIImage imageNamed:@"leftArrow"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backTheView)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    // Do any additional setup after loading the view.
    

}
#pragma mark - 板块设置区
- (void)isFirstOrNot{
    /** App判断第一次启动的方法 */
    NSString *key = @"CFBundleVersion";
    // 上一次的使用版本（存储在沙盒中的版本号）
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    // 当前软件的版本号（从Info.plist中获得）
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
    
    if ([currentVersion isEqualToString:lastVersion])
    {
        KDLog(@"不是第一次登录");

        // 版本号相同：这次打开和上次打开的是同一个版本
    }
    else
    {
        // 这次打开的版本和上一次不一样，显示新特性
        [self newUserGuide];
        KDLog(@"是第一次登录");

        // 将当前的版本号存进沙盒
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
- (void)setupNav{
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.center = CGPointMake(screenW / 2.0, screenH / 2.0);
    activityIndicator.color = [UIColor lightGrayColor];
    
    webUrl = [NSString stringWithFormat:@"%@mobile/index.html",ServerActionAddr2];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:activityIndicator];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(rightBarItemClick)];
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, screenW, 44)];
//    searchBar.showsCancelButton = YES;
    searchBar.placeholder = @"请输入网址";
    searchBar.delegate = self;
//    searchBar.showsSearchResultsButton = YES;
    self.navigationItem.titleView = searchBar;
    
    [self setupProgress];
    
}
/**
 *  设置进度条
 */
- (void)setupProgress{
    _webViewProgress = [[NJKWebViewProgress alloc] init];
    webview.delegate = _webViewProgress;
    _webViewProgress.webViewProxyDelegate = self;
    _webViewProgress.progressDelegate = self;
    
    
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,
                                 navBounds.size.height - 2,
                                 navBounds.size.width,
                                 2);
    _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_webViewProgressView setProgress:0 animated:YES];
    [self.navigationController.navigationBar addSubview:_webViewProgressView];
}
#pragma mark - 获取web内容
#pragma mark - 每次加载页面之前执行
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
     NSString *requestString = [[request URL] absoluteString];
    if([requestString isEqualToString:[NSString stringWithFormat:@"%@mobile/index.html",ServerActionAddr2]])
    {
        isBackMain = 1;
        
    }
    else
    {
        isBackMain = 2;
        if ([requestString  isEqual: @"https://www.youtube.com/"]) {
            webUrl = @"http://m.youtube.com/";
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:webUrl]];//@"http://192.168.1.221/mobile/index.html"
           NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:webUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
            [webview loadRequest:request];
            return NO;
        }
    }
    return YES;
}
#pragma mark - 事件点击区
- (void)rightBarItemClick{
    [webview reload];
}
#pragma mark - webview代理

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [activityIndicator startAnimating];

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    KDLog(@"%@", webView.request.URL.absoluteString);
    [activityIndicator stopAnimating];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [activityIndicator stopAnimating];
    
    KDLog(@"%@", error);
}

#pragma mark - 反回本界面
-(void)backTheView
{
    if (isBackMain == 2)//不是初始界面
    {
        if (webview.canGoBack) {
            [webview goBack];
        }else{
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:webUrl]];//@"http://192.168.1.221/mobile/index.html"
             NSURLRequest *request =[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:webUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
            [webview loadRequest:request];
        }
       
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    searchBar.showsCancelButton = YES;
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
//    NSLog(@"搜索Begin");
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//    NSLog(@"搜索End");
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    webUrl = [NSString stringWithFormat:@"http://%@",searchBar.text];
//    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:webUrl]];//@"http://192.168.1.221/mobile/index.html"
     NSURLRequest *request =[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:webUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    [webview loadRequest:request];
    [searchBar endEditing:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_webViewProgressView setProgress:progress animated:YES];
    self.title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
}

#pragma mark - 新手引导
- (void)newUserGuide
{
    // 这里创建指引在这个视图在window上(蒙版、手势)
    CGRect frame = [UIScreen mainScreen].bounds;
    UIView * bgView = [[UIView alloc]initWithFrame:frame];
    bgView.backgroundColor = GBColor(50, 50, 50, 0.8);
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sureTapClick:)];
    [bgView addGestureRecognizer:tap];
    
    //添加子视图控件
    UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 320, frame.size.width-10, 50)];
    textLabel.backgroundColor = [UIColor clearColor];
    textLabel.text = @"必看提示\n若发现无法正常访问境外网站，\n可退出登录账户，再完全退出app\n重新登录，即可～";
    textLabel.numberOfLines = 0;
    [textLabel sizeToFit];
    textLabel.centerX = bgView.centerX;
    textLabel.textColor = [UIColor whiteColor];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.font = [UIFont systemFontOfSize:16];
    [bgView addSubview:textLabel];
//    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(frame.size.width/2-30,115,100, 200)];;
//    imageView.image = [UIImage imageNamed:@"CouponBoard_guid"];
//    [bgView addSubview:imageView];
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    
    //create path 重点来了（这里需要添加第一个路径）
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
    // 这里添加第二个路径  （这个是矩形）
    [path appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(5, 64, frame.size.width-10, 50) cornerRadius:8] bezierPathByReversingPath]];
    
    //渲染
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
}
/**
 *   新手指引确定
 */
- (void)sureTapClick:(UITapGestureRecognizer *)tap
{
    UIView *guidevView = tap.view;
    [guidevView removeFromSuperview]; //移除蒙版
    [guidevView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];//移除所有子视图
    [guidevView removeGestureRecognizer:tap]; //移除手势
}

@end
